import React, { lazy, Suspense, useState } from 'react';
import { Card, Progress, Row, Col, Statistic, Tabs, Spin } from 'antd';
import { useUserStore } from '../../store/userStore';
import type { PlanetState } from '../../types';

// 懒加载3D星球组件
const Planet = lazy(() => 
  new Promise<{ default: React.ComponentType<any> }>((resolve) => {
    // 延迟1秒加载Planet组件，让页面先渲染基本内容
    setTimeout(() => 
      import('./Planet').then(module => {
        resolve({ default: module.Planet });
      }), 
    1000);
  })
);

const defaultPlanetState: PlanetState = {
  pollution: 0,
  biodiversity: 0,
  energy: { clean: 0, total: 1 },
  buildings: [],
  trees: 0,
  waterQuality: 0
};

const PlanetFallback = () => (
  <div style={{ 
    height: '600px', 
    width: '100%', 
    display: 'flex', 
    justifyContent: 'center', 
    alignItems: 'center',
    background: '#f5f5f5',
    borderRadius: '8px'
  }}>
    <Spin tip="加载3D星球..." size="large" />
  </div>
);

const MyPlanet: React.FC = () => {
  const { user } = useUserStore();
  const planetState = user?.planetState || defaultPlanetState;
  const [activeTab, setActiveTab] = useState('1'); // 默认显示数据标签页
  const [planetLoaded, setPlanetLoaded] = useState(false);

  const calculatePollutionLevel = (pollution: number) => {
    if (pollution <= 20) return '优';
    if (pollution <= 40) return '良';
    if (pollution <= 60) return '中';
    if (pollution <= 80) return '差';
    return '严重';
  };

  const calculateBiodiversityStatus = (biodiversity: number) => {
    if (biodiversity >= 80) return '丰富';
    if (biodiversity >= 60) return '良好';
    if (biodiversity >= 40) return '一般';
    if (biodiversity >= 20) return '较差';
    return '危险';
  };

  // 当切换到3D标签页时，标记为需要加载
  const handleTabChange = (key: string) => {
    setActiveTab(key);
    if (key === '2' && !planetLoaded) {
      setPlanetLoaded(true);
    }
  };

  const items = [
    {
      key: '1',
      label: '星球数据',
      children: (
        <Row gutter={[16, 16]}>
          <Col span={12}>
            <Card title="环境状况">
              <Statistic
                title="污染程度"
                value={calculatePollutionLevel(planetState.pollution)}
                valueStyle={{
                  color: planetState.pollution <= 40 ? '#3f8600' : '#cf1322',
                }}
              />
              <Progress
                percent={100 - planetState.pollution}
                status={planetState.pollution <= 40 ? 'success' : 'exception'}
                strokeColor={{
                  '0%': '#108ee9',
                  '100%': '#87d068',
                }}
              />
            </Card>
          </Col>
          <Col span={12}>
            <Card title="生态系统">
              <Statistic
                title="生物多样性"
                value={calculateBiodiversityStatus(planetState.biodiversity)}
                valueStyle={{
                  color: planetState.biodiversity >= 60 ? '#3f8600' : '#cf1322',
                }}
              />
              <Progress
                percent={planetState.biodiversity}
                status={planetState.biodiversity >= 60 ? 'success' : 'exception'}
                strokeColor={{
                  '0%': '#87d068',
                  '100%': '#108ee9',
                }}
              />
            </Card>
          </Col>
          <Col span={8}>
            <Card>
              <Statistic
                title="树木数量"
                value={planetState.trees}
                suffix="棵"
              />
            </Card>
          </Col>
          <Col span={8}>
            <Card>
              <Statistic
                title="水质指数"
                value={planetState.waterQuality}
                suffix="%"
                valueStyle={{
                  color: planetState.waterQuality >= 70 ? '#3f8600' : '#cf1322',
                }}
              />
            </Card>
          </Col>
          <Col span={8}>
            <Card>
              <Statistic
                title="清洁能源占比"
                value={(planetState.energy.clean / planetState.energy.total * 100).toFixed(1)}
                suffix="%"
                valueStyle={{
                  color: planetState.energy.clean / planetState.energy.total >= 0.5 ? '#3f8600' : '#cf1322',
                }}
              />
            </Card>
          </Col>
        </Row>
      ),
    },
    {
      key: '2',
      label: '3D星球',
      children: (
        <div style={{ height: '600px', width: '100%', position: 'relative' }}>
          {planetLoaded ? (
            <Suspense fallback={<PlanetFallback />}>
              <Planet />
            </Suspense>
          ) : (
            <PlanetFallback />
          )}
        </div>
      ),
    }
  ];

  return (
    <div style={{ padding: '24px' }}>
      <Card title="我的星球">
        <Tabs 
          defaultActiveKey="1" 
          items={items} 
          onChange={handleTabChange}
          activeKey={activeTab}
        />
      </Card>
    </div>
  );
};

export default MyPlanet; 